<?php
class CommentMapper{
    protected $table;
    protected $query;

    public function setTable($_table){
        $this->table = $_table;
        $this->query = 'SET NAMES utf8; SET CHARACTER SET utf8';
        return $this;
    }
    public function getTable(){
        return $this->table;
    }

    public function save($com){
        $arr = array(
            'text'      => $com->getText(),
            'user_id'   => $com->getUserid(),
            'msg_id'    => $com->getMessageid(),
            'date'      => $com->getDate()
        );
        $db = Database::getInstance();

        if(null == ($id = $com->getId())){
            $db->insert('comments', $arr);
        }else{
            $db->update('comments', $arr, $id);
        }
    }

    public function find($id, $com){
        $db = Database::getInstance();
        //$db = $reg->get('db');
        $data = $db->select('comments', $id);
        //echo $id;
        $com    ->setText($data['text'])
                ->setUserid($data['user_id'])
                ->setDate($data['date'])
                ->setMessageid($data['msg_id'])
                ->setId($id)
                ->setMapper($this);
    }

    public function delete($com){
        $db = Database::getInstance();;
        $db->delete('comments', $com->getId());
    }

    public function fetchAllComments($msg_id){
        $db = Database::getInstance();
        $resultSet = $db->fetchAll('comments WHERE msg_id = ' . $msg_id);
        $coms = array();
        //$messages = array();
        foreach($resultSet as $one){
            $com = new CommentModel();
            $com    ->setText($one['text'])
                    ->setDate($one['date'])
                    ->setUserid($one['user_id'])
                    ->setMessageid($one['msg_id'])
                    ->setId($one['id'])
                    ->setMapper($this);
            $coms[] = $com;
        }
        return $coms;
    }

    public function fetchAllCommentsToImage($img_id){
        $db = Database::getInstance();
        $resultSet = $db->fetchAll('img_comments WHERE img_id = ' . $img_id);
        $coms = array();
        //$messages = array();
        foreach($resultSet as $one){
            $com = new CommentModel();
            $com    ->setText($one['text'])
                    ->setDate($one['date'])
                    ->setUserid($one['user_id'])
                    ->setMessageid($one['img_id'])
                    ->setId($one['id'])
                    ->setMapper($this);
            $coms[] = $com;
        }
        return $coms;
    }

}
?>
